package com.consumer.config;

import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSON;
import com.consumer.entity.Log;
import com.consumer.entity.User;
import com.consumer.service.LogService;
import com.consumer.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

/**
 * @Description
 * @Author youxin
 * @Version V1.0.0
 * @Since 1.0
 * @Date 2021/11/16
 */
@Component
@Slf4j
public class LoginMessageLinstener implements MessageListenerConcurrently {
    @Autowired
    private LogService logService;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
        for (MessageExt msg:list) {
            Log logs=new Log();
            logs.setLoginTime(new Date());
            String uuid= UUID.randomUUID().toString();
            uuid=uuid.replace("-","");
            logs.setId(uuid);
            //TODO 获取登录成功消息
            try{
                String body=new String(msg.getBody(), StandardCharsets.UTF_8);
                log.info("LoginMessageLinstener consumeMessage {}",body);
                User user = JSON.parseObject(body, User.class);
                logs.setLoginName(user.getUsername());
                //TODO 利用redis 解决重复消费问题   加锁带上失效时间 防止程序问题导致的锁释放不了
                boolean lock = redisUtil.getLock(logs.getId(), 30000);
                if(lock){
                    //TODO 加锁成功数据入库
                    logService.saveLog(logs);
                }
            }catch (Exception e){
                log.error("consumerLoginMessage fail{}",e.getMessage());
             return ConsumeConcurrentlyStatus.RECONSUME_LATER;
            }finally {
                //TODO 记得别忘记释放锁
                redisUtil.releaseLock(logs.getId());
            }
        }
        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }
}
